import storage from '@/libs/storage';
import api from '@/api';
import eventBus from '@/libs/event-bus';
import { eventConf } from '@/config';
// import store from '@/store';

export default {

  getToken() {
    const user = storage.get('user');
    return user ? user.token : '';
  },

  getLang() {
    let language = storage.getLocal('language');
    if (!language) {
      language = window.navigator.language === 'zh-CN' ? 'zh' : 'en';
    }
    return language;
  },

  expireToLogin() {
    console.warn('dsadsad')
    storage.remove('user');
    storage.remove('authPathList');
    window.location.href = '/';
    eventBus.$emit(eventConf.ELOGOUT);
    Router.replace('/login');
    window.location.reload();
  },

  /**
   * 判断是否登录
   *
   * @returns
   */
  loggedIn(to) {
    const user = storage.get('user');
      const authPathList = storage.get('authPathList');
      let isInAuth = [];
      if(authPathList && authPathList.length >= 1) {
          isInAuth = authPathList.filter(item => {
              return item.url === to.path
          });
      }

    return new Promise((resolve, reject) => {
      if (user && user.token && isInAuth && isInAuth.length >= 1) {
        resolve();
      } else {
        reject();
      }
    });
  },
  
  login(params) {
    return new Promise((resolve, reject) => {
      api.user.login(params).then((response) => {
        const { status, data, msg, error } = response;
        if (status === '1' && error === '00000000') {
          const { username, id, skillTypeId, token, companyName, domain } = data;
          storage.set('user', {
              username,
              id,
              skillTypeId,
              token,
              companyName,
              domain
          });
          eventBus.$emit(eventConf.ELOGIN);
          // console.log(store.state.user.authority);
          // store.dispatch('getUserAuthority');
          resolve();
        } else {
          reject(msg);
        }
      });
    });
  },

  logout() {
    const user = storage.get('user');

    if (!(user && user.token)) {
      this.expireToLogin();
      return false;
    }

    const { token } = user;
    const params = {
      token
    };

    return new Promise((resolve, reject) => {
      api.user.logout(params).then((response) => {
        const { status } = response;
        if (status === '1') {
          this.expireToLogin();
          resolve();
        } else {
          reject();
        }
      });
    });
  }
};
